﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Security.Claims;

namespace Filters;

/// <summary>
/// 商户管理员特性
/// </summary>
public class StoreAttribute : Attribute, IActionFilter
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public void OnActionExecuted(ActionExecutedContext context)
    {

    }

    /// <summary>
    /// 检测商户管理员的登录权限和状态控制
    /// </summary>
    /// <param name="context"></param>
    public async void OnActionExecuting(ActionExecutingContext context)
    {
        var db = App.GetService<ISqlSugarClient>();

        if (checkIsHaveAllowAttr(context)) return;
       
        int storeId = App.User?.FindFirstValue("StoreId").ObjToInt() ?? 0;

        if (storeId == 0)
        {
            context.Result = new JsonResult(new { state = false, code = 401, msg = "请先登录" });

            return;
        }

        int storeState = await db.Queryable<Entity.Store>()

            .Where(x => x.Id == storeId)

            .WithCache(120)

            .Select(x => x.State)

            .FirstAsync();

        if (storeState is 0 or 2)
        {
            context.Result = new JsonResult(new { state = false, code = 200, msg = "商户审核中" });

            return;
        }

        if (storeState == 3)
        {
            context.Result = new JsonResult(new { state = false, code = 200, msg = "商户被禁用" });

            return;
        }

    }

    private bool checkIsHaveAllowAttr(ActionExecutingContext e)
    {
        var actionDesc = e.ActionDescriptor as ControllerActionDescriptor;

        if (actionDesc == null) return false;

        var attrs = actionDesc.MethodInfo.CustomAttributes;

        if (attrs == null || attrs.Count() == 0) return false;

        string [] names = attrs.Select(x=>x.AttributeType.Name).ToArray();

        return names.Contains("AllowAnonymousAttribute");
    }
}
